<template>
  <div>
    <el-form ref="stockForm" :model="stockForm" :rules="rules" label-width="130px" class="mar-l-20 mar-r-30">
      <el-form-item label="业务类型：" prop="businessType">
        <el-select v-model="stockForm.businessType" :disabled="businessTypeList.length == 1">
          <el-option v-for="(value, index) in businessTypeList" :key="index" :label="dict.businessType[value]"
            :value="value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="供应商：">
        <el-select v-model="stockForm.supplierId" :disabled="supplierEditDisable" placeholder="不限">
          <el-option label="不限" value=""></el-option>
          <el-option v-for="(item, index) in supplierList" :key="index" :label="item.supplierName"
            :value="item.supplierId"></el-option>
        </el-select>
      </el-form-item>
      <template v-if="stockForm.businessType == 10">
        <el-form-item label="收货地址：">
          <el-select class="width-130" v-model="stockForm.consigneeProvinceCode" placeholder="请选择省份" clearable
            @change="changeCity(stockForm.consigneeProvinceCode)">
            <el-option v-for="item in provinceList" :key="item.areaCode" :label="item.areaName" :value="item.areaCode">
            </el-option>
          </el-select>
          <el-select class="width-130" v-model="stockForm.consigneeCityCode" placeholder="请选择城市" clearable
            @change="changeDistrict(stockForm.consigneeCityCode)">
            <el-option v-for="item in cityList" :key="item.areaCode" :label="item.areaName" :value="item.areaCode">
            </el-option>
          </el-select>
          <el-select class="width-130" v-model="stockForm.consigneeDistrictCode" placeholder="请选择区县" clearable>
            <el-option v-for="item in districtList" :key="item.areaCode" :label="item.areaName" :value="item.areaCode">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="详细地址：">
          <el-input v-model="stockForm.consigneeAddress" placeholder="请输入详细地址"></el-input>
        </el-form-item>
        <el-form-item label="收货人：">
          <el-input v-model="stockForm.consignee" placeholder="请输入收货人姓名"></el-input>
        </el-form-item>
        <el-form-item label="收货人电话：">
          <el-input v-model="stockForm.consigneePhone" placeholder="请输入收货人电话" maxlength="11"
            oninput="this.value=this.value.replace(/^[0,2,3,4,5,6,7,8,9]*$/gi,'')"
            onkeyup="this.value=this.value.replace(/\D/g,'')">
          </el-input>
        </el-form-item>
      </template>
      <el-form-item label="备注：">
        <el-input type="textarea" v-model="stockForm.remark" :rows="3" class="width-300"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="doSave" :disabled="isInitComplate ? false:true">保存</el-button>
      <el-button @click="doCancel">取消</el-button>
    </div>
  </div>
</template>

<script>
  import {
    listSupplier
  } from '@/api/user/supplier'
  import {
    listProvince,
    listCity,
    listDistrict
  } from '@/api/area/area'
  import {
    saveStock,
    countStockGoods
  } from '@/api/warehouse/warehouseStock'
  import {
    getDictByGroupName
  } from '@/api/common/common'
  import {
    getWarehouse
  } from '@/api/warehouse/warehouseInfo'
  import {
    getPurchaseOrder
  } from '@/api/warehouse/purchaseOrder'

  export default {
    props: {
      showFlag: {
        type: Boolean,
        default: {}
      },
      // 出入库单对象
      stockOrder: {
        type: Object,
        default: {}
      }
    },
    watch: {
      showFlag(val) {
        if (val) {
          this.init()
        }
      }
    },
    data() {
      return {
        // 1: "采购入库"
        // 2: "销售退货"
        // 3: "调拨入库"
        // 4: "盘盈入库"
        // 5: "其他入库"
        // 6: "采购退货"
        // 7: "销售出库"
        // 8: "调拨出库"
        // 9: "盘亏出库"
        // 10: "其他出库"
        // 必填，业务属性下拉列表选择项
        businessTypeList: [],
        // 出入库表单
        stockForm: {
          stockId: '',
          businessType: '',
          supplierId: '',
          remark: '',
          stockSource: '',
          stockSourceNo: '',
          consigneeProvinceCode: '',
          consigneeCityCode: '',
          consigneeDistrictCode: '',
          consigneeAddress: '',
          consignee: '',
          consigneePhone: '',
          warehouseGoodsIds: [],
          supplierEditDisable: '',
          purchaseOrderId: ''
        },
        // 数据字典
        dict: {
          businessType: {}
        },
        // 表单规则
        rules: {
          businessType: [{
            required: true,
            message: '请选择城市',
            trigger: 'blur'
          }]
        },
        // 供应商是否可更改
        supplierEditDisable: false,
        // 仓库对象
        warehouseObj: {},
        // 供应商集合
        supplierList: [],
        // 省集合
        provinceList: [],
        // 市集合
        cityList: [],
        // 区集合
        districtList: [],
        // 是否初始化完成，为了防止还没请求接口结束，就点击保存
        isInitComplate: false
      }
    },
    created() {
      const supplierForm = {
        enterpriseId: this.getEnterpriseId()
      }
      if (this.stockOrder.stockSource === '1') {
        // 采购单来源的供应商特殊处理
        supplierForm.settlementType = 30
      }
      // 获取供应商列表
      listSupplier(supplierForm).then(response => {
        if (response.isError) return
        this.supplierList = response.data
      })
      // 获取省列表
      listProvince().then(response => {
        this.provinceList = response.data
      })
      // 初始化数据字典
      getDictByGroupName('WarehouseStockDTO').then(response => {
        this.dict = response.data
      })
      // 获取仓库信息
      getWarehouse(this.getWarehouseId()).then((response) => {
        if (response.isError) return
        this.warehouseObj = response.data
        // this.supplierEditDisable = this.warehouseObj.warehouseSource === 2
        if (this.warehouseObj.supplierId) {
          this.stockForm.supplierId = this.warehouseObj.supplierId
        }
      })
      this.init()
    },
    methods: {
      // 初始化
      init() {
        this.initForm()
        Object.assign(this.stockForm, this.stockOrder)
        const businessType = this.stockForm.businessType
        if (!businessType || businessType === 5 || businessType === 10) {
          this.businessTypeList = [5, 10]
        } else {
          this.businessTypeList = [businessType]
        }
        this.checkSupplier()
        // 判断是否有明细
        this.isInitComplate = false
        if (this.stockForm.purchaseOrderId) {
          getPurchaseOrder(this.stockForm.purchaseOrderId).then(response => {
            response.data.purchaseOrderGoodsList.forEach(goodsItem => this.stockForm.warehouseGoodsIds.push(
              goodsItem.warehouseGoodsId))
            this.isInitComplate = true
          })
        } else {
          this.isInitComplate = true
        }
      },
      // 初始化表单
      initForm() {
        const originData = this.$options.data()
        this.stockForm = originData.stockForm
        this.supplierEditDisable = false
      },
      // 判断供应商列表是否可更改
      checkSupplier() {
        if (this.stockOrder.disableSelectSupplier) {
          // 优先判断是否禁止选择供应商
          this.supplierEditDisable = true
          return
        }
        // 编辑出入库单时当出/入库单不包含明细时，可修改
        if (this.stockForm.stockId !== '') {
          countStockGoods(this.stockForm.stockId).then(response => {
            if (response.isError) return
            if (response.data > 0) {
              this.supplierEditDisable = true
            }
          })
        }
      },
      // 获取地址-市
      changeCity(provinceCode, cityCode, districtCode) {
        this.cityList = []
        this.districtList = []
        this.stockForm.consigneeCityCode = ''
        this.stockForm.consigneeDistrictCode = ''
        if (provinceCode) {
          listCity(provinceCode).then(response => {
            this.cityList = response.data
          })
          this.stockForm.consigneeCityCode = cityCode
          this.changeDistrict(cityCode, districtCode)
        }
      },
      // 获取地址-区
      changeDistrict(cityCode, districtCode) {
        this.districtList = []
        this.stockForm.consigneeDistrictCode = ''
        if (cityCode) {
          listDistrict(cityCode).then(response => {
            this.districtList = response.data
          })
          this.stockForm.consigneeDistrictCode = districtCode
        }
      },
      // 保存事件
      doSave() {
        this.$refs['stockForm'].validate((valid) => {
          if (valid) {
            this.stockForm.enterpriseId = this.getEnterpriseId()
            this.stockForm.warehouseId = this.getWarehouseId()
            if (this.stockForm.businessType === '6') {
              this.stockForm.stockSource = 2
            }
            saveStock(this.stockForm).then(response => {
              if (response.isError) return
              this.$message({
                message: '保存成功',
                type: 'success'
              })
              this.$router.push({
                path: '/stock/warehouse-stock-details/index',
                query: {
                  stockId: response.data
                }
              })
              this.$emit('callback', true)
            })
          }
        })
      },
      // 取消事件
      doCancel() {
        this.$emit('callback', false)
      }
    }
  }
</script>
